package com.hw8.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ehw8.base.domain.pojo.TokenItem;
import com.ehw8.base.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.xxtea.XXTEA;

/**
 * @author <a href='mailto:acttosma@gmail.com'>Acttos Ma</a>
 * @date 2019-11-18 20:22
 */
@Slf4j
public class JWTUtil {

    private static final String hmac256Key = "d9bfc5e41ccfb4402ca55dce527a3476636bd7e4";
    private static final String xxTeaKey = "88b73271b5cbc72d5a94706f89474025f9aea27f";


    public static TokenItem parseToken(String jwtToken) {
        Algorithm algorithm = Algorithm.HMAC256(hmac256Key);

        try {
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(jwtToken);

            String token = jwt.getId();
            token = XXTEA.decryptBase64StringToString(token, xxTeaKey);

            TokenItem ti = JSON.parseObject(token, TokenItem.class);

            if (null == ti) return null;

            if (ti.getExpiresAt().getTime() < TimeUtil.now().getTime()) {
                return null;
            }

            return ti;
        } catch (Exception e) {
            if (e.getClass().isInstance(JWTDecodeException.class)) {
                log.error("JWT Token解析失败，Token为老式Token或格式非法");
            }

            return null;
        }
    }

    public static void main(String[] args) {
        String[] tokens = {"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJIV0IiLCJqdGkiOiJRd2dXRWRocEJDU0laVmJ3bUtHUHRpQ2JnRTFhcWFlc0JQTEYxWTVRRVAybmdadTRFOENlRXB5KzRhUTkzQ2NVR2Zia0xlM3BZNVlhOTE3TkFvc1NRQ0daU2F1ZnRZU20ifQ.ru0T8qlwp8sniktI2u4uY-S4cYlvAjwv8cP0_bJnC3k","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJIV0IiLCJqdGkiOiJ3VzA3V2dJS2xTdkRHQUgrR1dWQVQvSHJFTnIwWERKNElaUUpmbi91Z2ZCSDBMcmJwVXZlTWQ3SmowU2lLOGozeDQ4bVBwWjBXSFdEMXBQUGZVVElQTmsrSHV5SDVncDIifQ.hJUaa1qsEg0qYCDY-zkGE2J0hNTk89g3Tdu9oikeUB8"};

        for (int i = 0; i< tokens.length; i++) {
            String token = tokens[i];
            System.out.println(token);
            TokenItem tokenItem = JWTUtil.parseToken(token);
            System.out.println(JSON.toJSONString(tokenItem));
        }
    }

}
